package com.novabluetooth.services.libecg.ecgdemo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ImageUtils;
import com.creative.base.BaseDate;
import com.creative.ecg.StatusMsg;
import com.health.R;
import com.health.model.PopDataBean;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.viewscontrols.NovaApplication;
import com.health.widget.PopWindow;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.services.libecg.bluetooth.ConnectActivity;
import com.novabluetooth.services.libecg.bluetooth.MyBluetoooth;
import com.novabluetooth.services.libecg.draw.BackGround;
import com.novabluetooth.services.libecg.draw.DrawThreadPC80B;
import com.novabluetooth.services.libecg.recvdata.ReceiveService;
import com.novabluetooth.services.libecg.recvdata.StaticReceive;
import com.novabluetooth.views.SBCLActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class MainPC80B extends Activity implements View.OnClickListener, PopupWindow.OnDismissListener {

	/**
	 * PC80B绘图的View
	 */
	private DrawThreadPC80B drawRunable;

	private BackGround drawBG;

	/**
	 * 绘图线程
	 */
	private Thread drawThread;

	private TextView tv_Gain, tv_HR, tv_MSG;

	private ImageView img_Battery, img_Smooth, img_Pulse;

	private Button btn_connect;

	private Button btn_back;


	/**
	 * 心电测量结果
	 */
	private String[] measureResult;
	private String hrResult;
	private String heartRate;
	// 心电图 图片
	private String ecgImgUrl;

	/**
	 * 电量等级
	 */
	private int batteryRes[] = { R.drawable.libecg_battery_0, R.drawable.libecg_battery_1,
			R.drawable.libecg_battery_2, R.drawable.libecg_battery_3 };

	private String IDCARD = "";
	private ARCHIVE_BASEINFO userInfo = null;

	/**
	 * PopWindow 实体bean
	 */
	List<PopDataBean> datasOptions = new ArrayList<>();
	private PopWindow popWindowOptions = null;
	//选中单条
	private int mnSeclectItem = -1;
	//单条id
	private String mnSeclectItemID = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置当前activity常亮 必须放在setContentView之前
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.libecg_main_context_pc80b);

		userInfo = NovaApplication.getUserInfo();
		if (userInfo != null) {
			IDCARD = userInfo.getIDCARD();
			if (TextUtils.isEmpty(IDCARD)) {
				return;
			}
		}

		startService(new Intent(this, ReceiveService.class));
		init();
	}

	private void init() {

		measureResult = getResources().getStringArray(R.array.ecg_measureres);
		tv_MSG = (TextView) findViewById(R.id.main_pc80B_MSG);
		tv_Gain = (TextView) findViewById(R.id.main_pc80B_title_gain);
		tv_HR = (TextView) findViewById(R.id.main_pc80B_title_hr);

		img_Battery = (ImageView) findViewById(R.id.main_pc80B_title_battery);
		img_Smooth = (ImageView) findViewById(R.id.main_pc80B_title_smooth);
		img_Pulse = (ImageView) findViewById(R.id.main_pc80B_title_pulse);

		drawRunable = (DrawThreadPC80B) findViewById(R.id.main_pc80B_view_draw);
		drawBG = (BackGround) findViewById(R.id.main_pc80B_view_bg);
		drawRunable.setmHandler(mHandler);

		btn_connect=(Button)findViewById(R.id.btn_connect);
		btn_connect.setOnClickListener(this);

		btn_back=(Button)findViewById(R.id.btn_back);
		btn_back.setOnClickListener(this);


		IntentFilter filter = new IntentFilter();
		filter.addAction(ReceiveService.ACTION_BLU_DISCONNECT);
		registerReceiver(receiver, filter);
	}

	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(ReceiveService.ACTION_BLU_DISCONNECT)) {
				Toast.makeText(MainPC80B.this, R.string.connect_connect_off,
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case StaticReceive.MSG_DATA_BATTERY: {
					setBattery(msg.arg1);
				}
				break;
				case BATTERY_ZERO: {// 电池电量为0时的消息
					if (img_Battery.isShown()) {
						img_Battery.setVisibility(View.INVISIBLE);
					} else {
						img_Battery.setVisibility(View.VISIBLE);
					}
					mHandler.sendEmptyMessageDelayed(BATTERY_ZERO, 500);
				}
				break;
				case StaticReceive.MSG_DATA_ECG_STATUS_CH: {
					switch (msg.arg1) {
						case StatusMsg.FILE_TRANSMIT_START: {// 接收文件
							setMSG(getResources().getString(
									R.string.measure_ecg_file_ing));
						}
						break;
						case StatusMsg.FILE_TRANSMIT_SUCCESS: {
							setMSG(getResources().getString(
									R.string.measure_ecg_file_end));
							Bundle data = msg.getData();
							String ecgFile = data.getString("ecgFile");
							int[] objs = data.getIntArray("obj");
							Log.e("xiaoxin", "handleMessage: " + ecgFile );
							Log.e("xiaoxin", "handleMessage: " + objs );
						}
						break;
						case StatusMsg.FILE_TRANSMIT_ERROR: {
							setMSG(getResources().getString(
									R.string.measure_ecg_time_err));
						}
						break;
						case StaticReceive.MSG_DATA_TIMEOUT: {
							setMSG(getResources().getString(
									R.string.measure_ecg_time_out));
						}
						break;
						case 4: {// 准备阶段波形
							if (drawRunable.isPause()) {
								drawRunable.Continue();
							}
							Bundle data = msg.getData();
							if (data.getBoolean("bLeadoff")) {
								setMSG(getResources().getString(
										R.string.measure_lead_off));
							} else {
								setMSG(" ");
							}
							setGain(data.getInt("nGain"));
						}
						break;
						case 5: {// 实时测量波形
							if (drawRunable.isPause()) {
								drawRunable.Continue();
							}
							Bundle data = msg.getData();
							if (data.getBoolean("bLeadoff")) {
								setMSG(getResources().getString(
										R.string.measure_lead_off));
							} else {
								setMSG(" ");
							}
							data.getInt("nTransMode");
							setHR(data.getInt("nHR"));
							setGain(data.getInt("nGain"));

						}
						break;
						case 6: {// 测量结果
							Bundle data = msg.getData();
							nTransMode = data.getInt("nTransMode");
							String time = data.getString("time");
							String ecgResult="";
							if (nTransMode == StatusMsg.TRANSMIT_MODE_QUICK
									&& time != null) {
								ecgResult = measureResult[data.getInt("nResult")];
								setMSG(ecgResult);
							} else {
								setMSG("");
							}
							drawRunable.cleanWaveData();
							drawRunable.Pause();
							setGain(0);
							int ecgHR = data.getInt("nHR");
							setHR(ecgHR);
							setSmooth(false);
							 //保存心电结果到数据库

//							Bitmap bitmap1 = ImageUtils.view2Bitmap(drawRunable);
//							Bitmap bitmap = createBitmap(drawRunable, drawRunable.getWidth(), drawRunable.getHeight());
//							File file = savePic1(bitmap1);
//							File file1 = savePic1(bitmap);
//
//							Log.e("eggggggggg", "handleMessage: " + file.toString() );
//							Log.e("eggggggggg", "handleMessage: " + file1.toString() );

							saveData("", ecgResult, String.valueOf(ecgHR));

						}
						break;
						case 7: {// 传输设置
							int nSmoothingMode = msg.arg2;// 滤波模式
							nTransMode = (Integer) msg.obj;// 传输模式
							if (nTransMode == StatusMsg.TRANSMIT_MODE_FILE) {
								setMSG(getResources().getString(
										R.string.measure_ecg_file_ing));
							} else if (nTransMode == StatusMsg.TRANSMIT_MODE_CONTINUOUS) {
								setMSG("");
								setSmooth(nSmoothingMode == StatusMsg.SMOOTHMODE_ENHANCE);
							}
						}
						break;
					}
				}
				break;
				case StaticReceive.MSG_DATA_PULSE: {
					showPulse(true);
				}
				break;
				case RECEIVEMSG_PULSE_OFF: {
					showPulse(false);
				}
				break;
			}
		}

	};

	/** 取消搏动标记 */
	public static final int RECEIVEMSG_PULSE_OFF = 0x115;

	/**
	 * 设置搏动标记
	 */
	private void showPulse(boolean isShow) {
		if (isShow) {
			img_Pulse.setVisibility(View.VISIBLE);
			new Thread() {
				@Override
				public void run() {
					super.run();
					try {
						Thread.sleep(50);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					mHandler.sendEmptyMessage(RECEIVEMSG_PULSE_OFF);
				}
			}.start();
		} else {
			img_Pulse.setVisibility(View.INVISIBLE);
		}
	}

	/**
	 * 当前数据传输模式
	 */
	private int nTransMode = 0;

	@Override
	protected void onResume() {
		super.onResume();
		if (drawThread == null) {
			drawThread = new Thread(drawRunable, "DrawPC80BThread");
			drawThread.start();
		}
		if (drawRunable.isPause()) {
			drawRunable.Continue();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (drawThread != null && !drawRunable.isPause()) {
			drawRunable.Pause();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		sendBroadcast(new Intent(ReceiveService.BLU_ACTION_DISCONNECT));
		if (!drawRunable.isStop()) {
			drawRunable.Stop();
		}
		drawThread = null;
		stopService(new Intent(this, ReceiveService.class));
		unregisterReceiver(receiver);
		back();
	}

	/** 消息 电池电量为0 */
	private static final int BATTERY_ZERO = 0x302;

	private void setBattery(int battery) {
		setImgResource(img_Battery, batteryRes[battery]);
		if (battery == 0) {
			if (!mHandler.hasMessages(BATTERY_ZERO)) {
				mHandler.sendEmptyMessage(BATTERY_ZERO);
			}
		} else {
			img_Battery.setVisibility(View.VISIBLE);
			mHandler.removeMessages(BATTERY_ZERO);
		}
	}



	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 0x100) {
			StaticReceive.setmHandler(mHandler);
		}
	}

	/**
	 * 设置滤波模式
	 *
	 * @param isVisible
	 */
	private void setSmooth(boolean isVisible) {
		setImgVisible(img_Smooth, isVisible);
	}

	/**
	 * 设置图片
	 *
	 * @param img
	 * @param res
	 */
	private void setImgResource(ImageView img, int res) {
		if (!img.isShown()) {
			img.setVisibility(View.VISIBLE);
		}
		img.setImageResource(res);
	}

	private void setImgVisible(ImageView img, boolean isVisible) {
		if (isVisible) {
			img.setVisibility(View.VISIBLE);
		} else {
			img.setVisibility(View.INVISIBLE);
		}
	}

	private void setGain(int gain) {
		System.out.println("setGain=" + gain);
		gain = gain <= 0 ? 2 : gain;
		setTVtext(tv_Gain, "x" + gain);
		drawRunable.setGain(gain);
		drawBG.setGain(gain);
	}

	private void setHR(int hr) {
		if (hr != 0) {
			setTVtext(tv_HR, "HR=" + hr);
		} else{
			setTVtext(tv_HR, "HR=--");
		}
	}

	private void setMSG(String msg) {
		setTVtext(tv_MSG, msg);
	}

	/**
	 * 设置TextView显示的内容
	 */
	private void setTVtext(TextView tv, String msg) {
		if (tv != null) {
			if (!tv.isShown()) {
				tv.setVisibility(View.VISIBLE);
			}
			if (msg != null && !msg.equals("")) {
				if (msg.equals("0")) {
					tv.setText(getResources().getString(
							R.string.const_data_nodata));
				} else {
					tv.setText(msg);
				}
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()){
			case R.id.btn_connect:
				initPopDatas();
				onPopwindowOptions();
				break;
			case R.id.btn_back:
				back();
				finish();
				break;
		}
	}

	private void back() {
		Intent intent = new Intent();
		intent.putExtra("heartRate",heartRate);
		intent.putExtra("hrResult",hrResult);
		intent.putExtra("ecgImgUrl",ecgImgUrl);
		setResult(Activity.RESULT_OK,intent);
	}

	@Override
	public void onBackPressed() {
		back();
		super.onBackPressed();
	}

	/**
	 * 保存结果到数据库
	 *
	 * @param imgUrl
	 * @param str_result
	 */
	private void saveData(String imgUrl, String str_result, String heartRate) {
		hrResult = str_result;
		this.heartRate = heartRate;
		this.ecgImgUrl = imgUrl;
		UUID uuidECG = UUID.randomUUID();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateECG = df.format(new Date());
		Log.e("eeeeeeeeeeeeeeeee2222", "ee_" + str_result);
		if (str_result == null) {
			str_result = "";
		}

		Log.e("xiaoxin", "saveData: " + hrResult + heartRate  +ecgImgUrl );

		DeviceShowSaveData.saveCLData("力康快速心电检测仪", "力康快速心电检测仪", "心电图片", imgUrl, "心电图片", uuidECG.toString(), IDCARD, dateECG);
		DeviceShowSaveData.saveCLData("力康快速心电检测仪", "力康快速心电检测仪", "心电诊断结果", str_result, "心电诊断结果", uuidECG.toString(), IDCARD, dateECG);
		DeviceShowSaveData.saveCLData("力康快速心电检测仪", "力康快速心电检测仪", "心率", heartRate, "心率", uuidECG.toString(), IDCARD, dateECG);
		JSONObject obj = new JSONObject();
		try {
			obj.put("heartRate",heartRate);
			obj.put("result",str_result);
			DeviceShowSaveData.saveCLData("力康快速心电检测仪", "力康快速心电检测仪", "心电json", obj.toString(), "心电json", uuidECG.toString(), IDCARD, dateECG);
		} catch (JSONException e) {
			e.printStackTrace();
		}



	}


	/**
	 * 初始化Popwindow
	 */
	private void initPopDatas() {
		if(datasOptions == null){
			datasOptions = new ArrayList<>();
		}

		datasOptions.clear();

		if (MyBluetoooth.isConnected) {
			datasOptions.add(new PopDataBean("0", "继续测量"));
			datasOptions.add(new PopDataBean("1", "断开连接"));
		} else {
			datasOptions.add(new PopDataBean("0", "连接设备"));
		}

		// 实例化PopWindow
		popWindowOptions = new PopWindow(this);
		// 设置点击其他位置mTestPopwindow2消失
		popWindowOptions.setOnDismissListener(this);
	}

	@Override
	public void onDismiss() {

	}
	private void onPopwindowOptions() {
		if (popWindowOptions == null) {
			return;
		}

		//回到接受
		popWindowOptions.setOnData(new PopWindow.OnGetData() {

			//记录上一次选中的item
			@Override
			public int onSeclectItem() {
				return mnSeclectItem;
			}

			@Override
			public void onDataCallBack(int nSectlect, ArrayList<PopDataBean> mArrayList) {
				mnSeclectItem = nSectlect;
				String name = mArrayList.get(nSectlect).getName();
				btn_connect.setText(name);

				mnSeclectItemID = mArrayList.get(nSectlect).getIndex();
				//设置操作事件
				clickPopData(mnSeclectItemID);
			}


			//传递数据源过去
			@Override
			public ArrayList<PopDataBean> onArrayList() {
				return (ArrayList<PopDataBean>) datasOptions;
			}
		});
		popWindowOptions.showAtLocation(btn_connect, Gravity.CENTER, 10, 10);
	}


	/**
	 * 设置操作事件
	 */
	private void clickPopData(String index) {
		if (MyBluetoooth.isConnected) {
			if("0".equals(index)){
				//0 继续测量
				startConncecDevice();
			}else if("1".equals(index)){
				//1 断开连接
				sendBroadcast(new Intent(ReceiveService.BLU_ACTION_DISCONNECT));
			}
		} else {
			startConncecDevice();
		}
	}

	/**
	 * 连接设备
	 */
	private void startConncecDevice() {
		Intent i = new Intent(this, ConnectActivity.class);
		i.putExtra("device", 3);
		startActivityForResult(i, 0x100);
	}


	public static Bitmap createBitmap(View v, int width, int height) {
		//测量使得view指定大小
		int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
		int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
		v.measure(measuredWidth, measuredHeight);
		//调用layout方法布局后，可以得到view的尺寸大小
		v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
		Bitmap bmp = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
		Canvas c = new Canvas(bmp);
		c.drawColor(Color.WHITE);
		v.draw(c);
		return bmp;
	}

	public static File savePic1(Bitmap bitmap){

		String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/followup/egg/";
		File rootFile = new File(path) ;
		if(!rootFile.exists()){
			rootFile.mkdirs() ;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyymmdd_hhmmss");
		String time = sdf.format(new Date(System.currentTimeMillis()));
		File file = new File(  path + time + ".jpg");
		try {
			FileOutputStream fos = new FileOutputStream(file) ;
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);// 把数据写入文件
			fos.flush() ;
			fos.close() ;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file;
	}


}
